<?php
/**
 * 
 * @author tangbl
 *
 */
class DictModel extends Model {
	
	/*array(
		0.字段名   
		1.验证规则 [require 字段必须、email 邮箱、url URL地址、currency 货币、number 数字]
		2.提示信息
		3.验证条件 [0.(默认)存在字段就验证;1.必须验证;2.值不为空的时候验证]
		4.附加规则 [regex、function、callback、confirm、equal、in、length、between、expire、ip_allow、ip_deny、unique]
		5.验证时   [1.新增数据时候验证;2.编辑数据时候验证;3.(默认)全部情况下验证]
	);*/
	protected $_validate    =   array(
		//array('key','','字典标识不能重复',1,'unique',1),
		array('type','require','必须选择字典类型',1,'',1),
	);
	
	// 定义自动完成
	protected $_auto    =   array(
		array('addtime','time',1,'function'),//add
		
	);
	
	//得到一级字典
	public function getTopDict(){
		$map['pid']   = 0 ;
		$map['level'] = 1 ;
		return $this->where($map)->select();
	}
	
	//重新生成所有字典缓存
	function cacheDict(){
		$list = $this->getTopDict();
		foreach($list as $k=>$v){
			$this->getDictByKey($v['key'],true);
		}
	}
	
	//得到数据字典的根
	public function getRootDict($key){
		$map['level'] = 1 ;
		$map['pid']   = 0 ;
		$map['key']   = $key ;
		
		return $this->where($map)->find();
	}

	//更新字典缓存
	public function getDictByKey($key,$flag=true) {
		
		$list = F('Dict_'.$key);
		if($flag || empty($list)){
			$map['key'] = $key ;
			$order = "sort desc";
			$list  = $this->where($map)->order($order)->select();
			foreach($list as $k=>$v){
				if($v['pid']){
					$id    = $v["id"];
					$title = json_decode($v["value"],true);
					$row[$id] = $title;
				}
			}
			F('Dict_Value_'.$key,$row);
			F('Dict_'.$key,$list);
		}
		return $list;
	}
	
	//更新父级字典是否有下级(haveLeaf)
	public function updLeaf($id,$flag=false){
		$haveLeaf  = 1;
		if($flag){
			$num = $this->where("pid = $id")->count();
			if($num == 0){
				$haveLeaf = 2 ;
			}
		}
		
		$data['id']        = $id;
		$data['haveLeaf']  = $haveLeaf;
		$this->data($data)->save();
	}
	
	//更新根字典(total)
	public function updTotal($key){
		$root = $this->getRootDict($key);
		$max  = $this->where(array("key"=>$key))->max("level");
		$data = array("id"=>$root['id'],"total"=>($max-1));
		$this->data($data)->save();
	}
	
	//生成字典level、haveLeaf、
	public function genDict($pid,$id,$key){
		
		if($pid){
			
			//更新父节点
			$this->updLeaf($pid,false);
			
			//更新level
			$parent = $this->find($pid);
			$data['level'] = intval($parent['level'])+1;
			if(is_array($id)){
				$map['pid'] = $pid ;
			}else{
				$map['id']  = $id ;
			}
			$this->where($map)->save($data);
			
		}else{
			$data['level']    = 1 ;
			$data['total']    = 0 ;
			$data['haveLeaf'] = 2 ;
			$data['id']       = $id ;
			$this->data($data)->save();
			
		}
		$this->updTotal($key);
		//更新对应key的缓存
		$this->getDictByKey($key);
	}

	
}
?>